import fitz  # PyMuPDF
import os
import hashlib

def save_poly_image_from_pdf(
    pdf_path,
    page_id,
    poly_flat,
    expected_pixel_size,
    output_dir="cropped_images"
):
    """
    裁剪PDF指定页面的区域为图像，自动缩放至目标页面大小，并用像素坐标hash生成文件名

    Args:
        pdf_path (str): PDF文件路径
        page_id (int): 页码（从0开始）
        poly_flat (list): 多边形区域的像素坐标 [x1, y1, ..., xn, yn]
        expected_pixel_size (tuple): 希望渲染后整页为多少像素 (width_px, height_px)
        output_dir (str): 图像输出目录

    Returns:
        tuple: (保存路径, 页面像素宽高)
    """
    if len(poly_flat) % 2 != 0:
        raise ValueError("poly 坐标数量必须为偶数")

    # 打开 PDF 页面，获取逻辑尺寸（point）
    doc = fitz.open(pdf_path)
    page = doc[page_id]
    width_pt, height_pt = page.rect.width, page.rect.height

    # 根据期望像素尺寸计算 DPI
    target_w_px, target_h_px = expected_pixel_size
    dpi_x = target_w_px * 72 / width_pt
    dpi_y = target_h_px * 72 / height_pt
    dpi = (dpi_x + dpi_y) / 2
    scale = dpi / 72
    matrix = fitz.Matrix(scale, scale)

    # 页面实际像素大小
    pix = page.get_pixmap(matrix=matrix)
    page_pixel_size = (pix.width, pix.height)

    # 将像素坐标转换回逻辑坐标（/scale）
    poly_pts = [(x / scale, y / scale) for x, y in zip(poly_flat[::2], poly_flat[1::2])]

    # 计算裁剪矩形（最小包含所有点）
    xs, ys = zip(*poly_pts)
    rect = fitz.Rect(min(xs), min(ys), max(xs), max(ys))

    # 获取裁剪图像
    clip_pix = page.get_pixmap(matrix=matrix, clip=rect)

    # 构建hash文件名（仅由 poly_flat 决定）
    poly_str = ",".join(str(int(v)) for v in poly_flat)
    filename_hash = hashlib.md5(poly_str.encode("utf-8")).hexdigest()
    filename = f"{filename_hash}.png"

    # 保存图像
    os.makedirs(output_dir, exist_ok=True)
    image_path = os.path.join(output_dir, filename)
    clip_pix.save(image_path)

    return image_path, page_pixel_size




if __name__ == "__main__":
    # 示例PDF路径和多边形坐标
    pdf_path = "/home/fengjie/doc-parser/MinerU/src/input_doc/sample/提取自26.pdf"
    page_id = 1  # 第1页
    poly = [94,211,1555,211,1555,2096,94,2096]  # 示例多边形坐标
    expected_pixel_size = (1654, 2339) # 期望的图像大小

    # 调用函数保存图像
    image_path,page_size = save_poly_image_from_pdf(pdf_path, page_id, poly,expected_pixel_size)
    print(f"保存的图像路径: {image_path}")
    print("页面大小：", page_size)